(function ($) {

    if(!$){
        return;
    }
    /*
        pWidth:不输默认为400
        pHeight：默认和宽度一样
        domain:图片访问url
        titlelabelnm：上传的描述
        previewlabelnm：预览的描述
        multifiles:是否为多个 默认为1多个，0单个
        multiSize:10 默认最多十个
        withdefault:1 (与multifiles配合使用，为1时，有默认模块)
        withpreview:1 预览控件 默认有
        withtext:1 文本输入框显示url 默认无
        params:参数
        url=[多个时格式{id:url,id:url,id:url}]
        attrNm=:默认imageurl
        support:[.mp4,.ogg,.webm]
    */
    var FileManager = function(){
        return {
            init:function(fileManager){
                if(!fileManager){
                    return;
                }
                var _this = this;
                _this.fileManager = fileManager;
                _this.configProps = _this.properties();
                _this.filers = fileManager.find(".fileinputers");
                if($(fileManager).hasClass("inited")){
                    return _this;
                }
                $(fileManager).prop("id",(_this.configProps.attrNm +"_manager"));
                $(fileManager).addClass("inited")
                if(_this.configProps.multifiles == "1"){
                    _this.bindEvents();
                }
                _this.genBySetting();
                return _this;
            },
            bindEvents:function(){
                var _this = this;
                $(_this.fileManager).find(".mng-tool").on("click",function(){
                    var tg = $(this).attr("tg");
                    if(tg == "add"){
                        _this.genBySetting();
                    }else if(tg == "del"){
                        _this.delFiler();
                    }
                });
            },
            properties:function(){
                var _this = this;
                var fileManager = _this.fileManager;
                var pWidth = $(fileManager).attr("pWidth") || "400";
                var pHeight = $(fileManager).attr("pHeight") || pWidth;
                var url = $(fileManager).attr("url") ||"";
                var domain = $(fileManager).attr("domain") || "";
                var attrNm = $(fileManager).attr("attrNm") || 'imageurl';
                var params = $(fileManager).attr("params")||"";
                var accept = $(fileManager).attr("accept")||"*";
                var multifiles = $(fileManager).attr("multifiles") || "0";
                var withpreview = $(fileManager).attr("withpreview") || "1";
                var withtext = $(fileManager).attr("withtext") || "0";
                var titlelabelnm = $(fileManager).attr("titlelabelnm") || "上传图片内容";
                var previewlabelnm = $(fileManager).attr("previewlabelnm") || "上传图片预览";
                var withdefault = $(fileManager).attr("withdefault") || "1";
                return{
                    pWidth:pWidth,
                    pHeight:pHeight,
                    url:url,
                    domain:domain,
                    attrNm:attrNm,
                    params:params,
                    accept:accept,
                    multifiles:multifiles,
                    withpreview:withpreview,
                    withtext:withtext,
                    previewlabelnm:previewlabelnm,
                    titlelabelnm:titlelabelnm,
                    withdefault:withdefault
                };
            },
            genMultiFilesPart:function(){
                var _this = this;
                var domain  = _this.configProps.domain + "";
                if(_this.configProps.url){
                    var urls = _this.configProps.url.split(",");
                    $(urls).each(function(idx){
                        var arr = this.split(":");
                        var tmp = $.extend({},_this.configProps,{url:arr[1],id:arr[0],idx:idx});
                        var inputer = UploadHtmlGenerator.genInputer(_this.configProps);
                        $(inputer).attr("url",domain + arr[1]);
                        FileInput.init(inputer);
                        _this.filers.append($(inputer));
                    });
                }else{
                    if(_this.configProps.withdefault){
                        var inputer = UploadHtmlGenerator.genInputer(_this.configProps);
                        $(inputer).attr("idx",1);
                        FileInput.init(inputer);
                        _this.filers.append($(inputer));
                    }
                }
            },
            genSingleFilePart:function(){
                var _this = this;
                var domain  = _this.configProps.domain + "";
                var inputer = UploadHtmlGenerator.genInputer(_this.configProps);
                if(_this.configProps.url){
                    $(inputer).attr("url",domain + _this.configProps.url);
                }
                FileInput.init(inputer);
                _this.filers.append($(inputer));
            },
            genBySetting:function(){
                var _this = this;
                if(_this.configProps.multifiles == "1"){
                    _this.genMultiFilesPart();
                }else{
                    _this.genSingleFilePart();
                }
            },
            delFiler:function(){
                var _this = this;
                var length = $(_this.filers).children().length;
                var idx = length - 1;
                if(length == 0){
                    return;
                }
                var child = $(_this.filers).children()[idx];
                $(child).remove();
            },
            getVal:function(){
                var _this = this;
                var res;
                $(_this.filers).children().each(function(){
                    if(_this.configProps.multifiles == "1"){
                        res = res || [];
                        var inpVal = $(this).find(".file-inp-tool").val();
                        if(inpVal){
                            res.push(inpVal);
                        }
                    }else{
                        res = $(this).find(".file-inp-tool").val();
                    }
                });
                return res;
            }
        }
    };

    var UploadHtmlGenerator = (function(){
        var inputTool = {
            genUploader:function(properties){
                var html = "";
                if(properties.withtext == "1"){
                    html +='<div class="form-group row">   ';
                    html +='    <label class="col-lg-2 col-form-label">' + properties.titlelabelnm + '：</label>   ';
                    html +='    <div class="col-lg-10"> ';
                    html +='        <div class="row">';
                    html +='            <div class="col-lg-7">';
                    html +='                <input type="text" id="' + properties.attrNm + '"   name="' + properties.attrNm + '" class="form-control file-inp-tool">    ';
                    html +='            </div>';
                    html +='            <div class="col-lg-5">';
                    html +='                <label class="btn btn-sm btn-primary">上传文件</label>     ';
                    html +='                <input type="file" style="visibility:hidden" id="edit_image"  accept="' + properties.accept + '" >';
                    html +='            </div>';
                    html +='        </div>';
                    html +='    </div>';
                    html +='</div>';
                }else{
                    html +='<div class="form-group row">   ';
                    html +='    <label class="col-lg-2 col-form-label">' + properties.titlelabelnm + '：</label>   ';
                    html +='    <div class="col-lg-10">        ';
                    html +='        <label class="btn btn-sm btn-primary">上传文件</label>         ';
                    html +='        <input class="file-inp-tool" type="hidden" name="' + properties.attrNm + '"  id="' + properties.attrNm + '" > ';
                    html +='        <input type="file" style="visibility:hidden" id="edit_image" accept="' + properties.accept + '" >   ';
                    html +='    </div>';
                    html +='</div>';
                }
                return html;
            },
            genPreview:function(properties){
                var html = "";
                html +='<div class="form-group row">   ' ;
                html +='    <label class="col-lg-2 col-form-label">' + properties.previewlabelnm + '：</label>   ' ;
                html +='    <div class="col-lg-10">     ' ;
                html +='        <div class="filer-preview" style="margin: auto; display: inline-block; width: 400px; height: 400px;">' ;
                html +='        </div>   ';
                html +='    </div>' ;
                html +='</div>';
                return html;
            },
            setInputProp:function(inputer,properties){
                for(var key in properties){
                    if(key != "url" && key != "accept"){
                        $(inputer).attr(key,properties[key]);
                    }
                }
            }
        };
        var _this = this;
        return {
            genInputer:function(properties){
                var html = "";
                var inputer = $('<div class="fileInputer">');
                inputTool.setInputProp(inputer, properties);
                var uploaderHtml = inputTool.genUploader(properties);
                inputer.append($(uploaderHtml));
                if(properties.withpreview == "1"){
                    var previewHtml = inputTool.genPreview(properties);
                    inputer.append($(previewHtml));
                }
                return inputer;
            }
        };
    })();

    var FileInput = (function(){
        return {
            init:function(inputer){
                if(!inputer){
                    return;
                }
                var _this = this;
                _this.inputer = inputer;
                _this.initVal();
                _this.setPreview(inputer);
                _this.bindEvents(inputer);
            },
            initVal:function(){
                var _this = this;
                var properties = _this.getFilerProperties(_this.inputer);
                if(properties.url){
                    _this.inputer.find(".file-inp-tool").val(properties.url);
                }
            },
            setPreview:function(inputer){
                var _this = this;
                var previews = $(inputer).find(".filer-preview");
                if(previews){
                    var properties = _this.getFilerProperties(inputer);
                    if(properties.withPriview == "1"){
                        FilePreview.preview(previews[0],properties.pWidth,properties.pHeight,properties.domain + "/" +  properties.url);
                    }
                }
            },
            getFilerProperties:function(inputer){
                var pWidth = $(inputer).attr("pWidth");
                var pHeight = $(inputer).attr("pHeight");
                var url = $(inputer).attr("url");
                var domain = $(inputer).attr("domain") || "";
                var attrNm = $(inputer).attr("attrNm");
                var params = $(inputer).attr("params");
                var withPriview = $(inputer).attr("withPreview") || "1";
                var paramObj = {};
                if(params){
                    var paramArr = params.split("&");
                    for(var str in paramArr){
                        var keyVal = paramArr[str].split("=");
                        paramObj[keyVal[0]] = keyVal[1];
                    }
                }
                return {
                    pWidth:pWidth,
                    pHeight:pHeight||pWidth,
                    url:url||"",
                    attrNm:attrNm,
                    withPriview:withPriview,
                    domain:domain,
                    paramObj:paramObj
                };
            },
            bindEvents:function(inputer){
                var _this = this;
                var uploading = false;
                $(inputer).find(".btn").on("click",function(){
                    $(inputer).find("input[type=file]").click();
                });
                $(inputer).find("input[type=file]").on("change",function(){
                    if(this.files && this.files.length > 0){
                        var imgData = new FormData();
                        imgData.append("file",this.files[0]);
                        var properties = _this.getFilerProperties(inputer);
                        for(var key in properties.paramObj){
                            imgData.append(key,properties.paramObj[key]);
                        }
                        if(uploading){
                            alert("文件正在上传中，请稍候");
                            return;
                        }
                        $.ajax({
                            url: "/cms_media_upload",
                            type: 'POST',
                            cache: false,
                            data: imgData,
                            processData: false,
                            dataType:"json",
                            contentType : false,
                            beforeSend: function(){
                                uploading = true;
                            },
                            success : function(data) {
                                if(data.success){
                                    var attrNm = $(inputer).attr("attrnm");
                                    $(inputer).find("input[name=" +  attrNm + "]").val(data.data);
                                    $(inputer).attr("url",data.data);
                                    _this.setPreview(inputer);
                                }
                                uploading = false;
                            },
                            complete :function(XHR, TS){
                                uploading = false;
                            }
                        });
                        _this.setPreview(inputer);
                        uploading = false;
                    }
                });
            }
        }
    })($);

    var FilePreview = (function(){
        return {
            preview:function(preview,pWidth,pHeight,url){
                if(isNaN(pHeight)){
                    pHeight = pWidth;
                }
                $(preview).css({
                    "width":pWidth+"px",
                    "height":pHeight+"px"
                });

                if(url.indexOf("_")==-1){
                    var mt = (pHeight-22)/2;
                    if(url.length>40){ // 地址小于40可能只是域名，没有图片路径
                        var p1 = url.split(".");
                        $(preview).html("<div style='font-weight:bold; font-size:16px; display:block; text-align:center; color:#999; margin-top:"+mt+"px;'>"+p1[1]+"</div>");
                    }else{
                        $(preview).html("<div style='font-weight:bold; font-size:16px; display:block; text-align:center; color:#999; margin-top:"+mt+"px;'>暂无</div>");
                    }
                }else{
                    var p1 = url.split("_");
                    var p2 = p1[1].split(".");
                    var p3 = p2[0].split("x");
                    var iw = p3[0];
                    var ih = p3[1];
                    var ext = p2[1];

                    var dv = pWidth/pHeight;
                    var iv = iw/ih;

                    var rw = 0;
                    var rh = 0;
                    var ml = 0;

                    if(dv>=iv){
                        rh = pHeight;
                        rw = iw*rh/ih;
                        ml = (pWidth-rw)/2;
                    }else{
                        rw = pWidth;
                        rh = ih*rw/iw;
                    }

                    var img = "<a href='"+url+"' target='_blank'>";
                    img += "<img src='"+url+"' width='"+rw+"' height='"+rh+"' style='display:inline-block; margin-left:"+ml+"px;' />";
                    img += "</a>";
                    $(preview).html(img);
                }
            }
        };

    })($);

    $.fn.extend({
        redirFileInputer:function(){
            $(this).each(function(){
                FileInput.init($(this));
            });
        },
        filesManger:function(){
            if(this.length == 1){
                var mg = new FileManager();
                return mg.init($(this));
            }
            $(this).each(function(){
                var mg = new FileManager();
                mg.init($(this));
            })
        }
    });
    $(".filesManager").filesManger();
})(jQuery);